<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\admin\model\kuerp\Commonseal;
use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use app\admin\model\kuerp\GoodsSales;
use app\admin\model\kuerp\Expense;
use app\admin\model\ScoreApply;
use think\Config;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        $cookieArr = ['adminskin' => "/^skin\-([a-z\-]+)\$/i", 'multiplenav' => "/^(0|1)\$/", 'multipletab' => "/^(0|1)\$/", 'show_submenu' => "/^(0|1)\$/"];
        foreach ($cookieArr as $key => $regex) {
            $cookieValue = $this->request->cookie($key);
            if (!is_null($cookieValue) && preg_match($regex, $cookieValue)) {
                config('fastadmin.' . $key, $cookieValue);
            }
        }
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $childrenSales = $this->auth->childrenSales;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $childrenSales = array_merge($childrenSales,$config_sale_users);
        }
        //报销单审批
        $expense = 0;
        if ($this->auth->check('examine/expense/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $wheres['check_step_sort'] = $examine_index - 1;
                    $expense = Expense::where($wheres)->count();
                }
            }
        }
        //获取直属下级
        $children_ids = [];
        $department_ids = Admin::getPrincipalIds($this->auth->id);
        if ($department_ids) {
            $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
            $children_ids = array_unique(array_merge($children_ids, !empty($config_examine_admins[$this->auth->id]) ? explode(',', $config_examine_admins[$this->auth->id]) : []));
        }

        $examine = 0;
        if ($this->auth->check('examine/goods_sales/examine')) {
            $wheres = [
                // 'purchase_time' => $where['createtime'],
                'sale_user' => ['in', $childrenSales],
                'examine_status' => 0,
                'examine_adminids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $first_children_ids = [];
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        //获取直属下级
                        // $department_ids = Admin::getPrincipalIds($this->auth->id);
                        // if ($department_ids) {
                            // $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                            // $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                            if ($children_ids) {
                                $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                            }
                        // }
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $first_children_ids).'))  OR (examine_index '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and sale_user in ('.implode(',', $childrenSales).')))')];
                        } else {
                            $wheres['examine_index'] = 0;
                        }
                    } else {
                        $wheres['examine_index'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    $examine = GoodsSales::where($wheres)->count();
                }
            }
        }
        //积分申请单审批
        $score = 0;
        if ($this->auth->check('score_apply/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                
                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $score = ScoreApply::where($wheres)->count();
                }
            }
        }

        //待审核公章申请单
        $commonseal = 0;
        if ($this->auth->check('kuerp/commonseal/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }

                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $commonseal = Commonseal::where($wheres)->count();
                }
            }
        }

        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'examine' => [($examine + $expense + $score + $commonseal), 'red', 'badge'],
            'examine/goods_sales' => [$examine, 'red', 'badge'],
            'examine/expense' => [$expense, 'red', 'badge'],
            'score_apply/examinelist' => [$score, 'red', 'badge'],
            'kuerp/commonseal/examinelist' => [$commonseal, 'red', 'badge'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->assignconfig('cookie', ['prefix' => config('cookie.prefix')]);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', '', 'url_clean');
        $url = $url ?: 'index/index';
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        //保持会话有效时长，单位:小时
        $keeyloginhours = 24;
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password', '', null);
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? $keeyloginhours * 3600 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect($url);
        }
        $background = Config::get('site.login_background');//Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('keeyloginhours', $keeyloginhours);
        $this->view->assign('background', $background);
        $title = Config::get('site.name');
        $logo = Config::get('site.logo');
        $this->view->assign('title', $title ?? __('Login'));
        $this->view->assign('logo', $logo ? cdnurl($logo) : '');
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->auth->logout();
            Hook::listen("admin_logout_after", $this->request);
            $this->success(__('Logout successful'), 'index/login');
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

}
